package org.ricks.net.http.restful;

import org.ricks.ioc.BeanAnalysisProcessor;
import org.ricks.ioc.HotfixManager;
import org.ricks.ioc.anno.Controller;
import org.ricks.ioc.utils.IocException;
import org.ricks.ioc.utils.Logger;

import java.util.Objects;

public class ControllerRegisterProcessor implements BeanAnalysisProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean) throws IocException {
        // 优先使用热更后的类
        Class<?> actualClass = HotfixManager.getHotfixClass(bean.getClass().getName());
        if (actualClass != null) {
            try {
                // 创建热更后的实例并复制字段值
                Object hotfixBean = actualClass.newInstance();
                copyFieldValues(bean, hotfixBean);
                bean = hotfixBean;
            } catch (Exception e) {
                Logger.error("创建热更Action实例失败", e);
            }
        }
        var clazz = bean.getClass();
        Controller controller = clazz.getAnnotation(Controller.class);
        if(Objects.isNull(controller)) return bean;
        RestfulBootstrap.getInstance().addController(bean);
        return bean;
    }

}
